<template>
  <a-modal
    :open="visible"
    :keyboard="false"
    :maskClosable="false"
    title="测试接口"
    @cancel="onCancel"
    :footer="false"
    :width="900"
  >
    <a-card title="参数请求" size="small" :loading="loading">
      <a-form ref="formRef" v-bind="formLayout">
        <a-form-item
          :label="item.description || item.name"
          v-for="(item, index) in config.requestOptions"
          :key="index"
        >
          <a-input
            v-model:value="formModel[item.name]"
            :placeholder="'请输入参数【' + item.name + '】'"
          ></a-input>
        </a-form-item>
      </a-form>
      <template #extra>
        <a-button
          type="primary"
          @click="sendRequest"
          :loading="loading"
          size="small"
        >
          发送请求
        </a-button>
      </template>
    </a-card>
    <a-card
      title="响应结果"
      size="small"
      style="margin-top: 15px"
      :loading="loading"
    >
      <monaco-editor
        :readonly="true"
        :value="responseData"
        v-if="responseData"
      />
      <span v-else>未返回结果</span>
    </a-card>
  </a-modal>
</template>

<script lang="ts" setup>
import { HttpApiConfigDto } from "@/api/report/types";
import { ref } from "vue";
import api from "@/api/report/httpApiConfig";
interface IHttpApiTestProps {
  visible: boolean;
  config: HttpApiConfigDto;
}
const props = defineProps<IHttpApiTestProps>();
const emits = defineEmits(["close", "update:visible"]);

const formModel = ref<Record<string, any>>({});
const responseData = ref<string>();
/**
 * 表单布局方式
 */
const formLayout = {
  labelCol: { span: 3 },
  labelAlign: "right",
  wrapperCol: { span: 20 },
};

/**
 * 发送请求
 */
const loading = ref(false);

/**
 * 取消
 */
const onCancel = () => {
  emits("update:visible", false);
  emits("close");
};

/**
 * 发送请求
 */
const sendRequest = () => {
  loading.value = true;
  api
    .query(props.config.code, formModel.value)
    .then((res) => {
      if (typeof res == "string") {
        responseData.value = res;
      } else {
        responseData.value = JSON.stringify(res, null, 4);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>

<style lang="less" scoped></style>
